//
//  BCTBSettingViewController.m
//  BCOpenTb
//
//  Created by yuhanle on 2017/1/16.
//  Copyright © 2017年 tilink. All rights reserved.
//

#import "BCTBSettingViewController.h"
#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import <AlibabaAuthSDK/ALBBSDK.h>
#import <TBAppLinkSDK/TBAppLinkSDK.h>
#import <UIImageView+WebCache.h>

@interface BCTBSettingViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIButton *tbAuthAction;
@property (weak, nonatomic) IBOutlet UIButton *orderBtn;

@end

@implementation BCTBSettingViewController

- (IBAction)tbAuthEvent:(UIButton *)sender {
    BOOL isAuth = [[ALBBSession sharedInstance] isLogin];
    
    if (!isAuth) {
        [[ALBBSDK sharedInstance] auth:self successCallback:^(ALBBSession *session) {
            [self refresUserInfo];
            [self performSelector:@selector(refresUserInfo) withObject:nil afterDelay:1.0];
        } failureCallback:^(ALBBSession *session, NSError *error) {
            
        }];
        
    }else {
        [[ALBBSDK sharedInstance] logout];
        [self refresUserInfo];
        
        [self performSelector:@selector(refresUserInfo) withObject:nil afterDelay:1.0];
    }
}

#pragma mark - Life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

- (void)refresUserInfo {
    BOOL isAuth = [[ALBBSession sharedInstance] isLogin];
    
    if (isAuth) {
        ALBBUser *user = [[ALBBSession sharedInstance] getUser];
        
        self.orderBtn.hidden = NO;
        self.nameLabel.text = user.nick;
        [self.tbAuthAction setTitle:@"取消授权" forState:UIControlStateNormal];
        [self.avatarImageView sd_setImageWithURL:[NSURL URLWithString:user.avatarUrl]];
    }else {
        self.orderBtn.hidden = YES;
        self.nameLabel.text = @"未登录";
        [self.tbAuthAction setTitle:@"淘宝授权登陆" forState:UIControlStateNormal];
        [self.avatarImageView setImage:nil];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refresUserInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
